#include <iostream>
#include <unistd.h>
#include <pthread.h>

using namespace std;

#define NUM 5

void* threadRun(void *name)
{
    while(true)
    {
        cout << "我是次线程 " << (char*)name << endl;
        sleep(1);
    }
    delete[] (char*)name;

    return nullptr;
}

int main()
{
    pthread_t pt[NUM];

    for(int i = 0; i < NUM; i++)
    {
        // 注册新线程的信息
        char *name = new char[64];
        snprintf(name, 64, "thread-%d", i + 1);
        pthread_create(pt + i, nullptr, threadRun, name);
    }

    // 等待次线程运行结束
    for(int i = 0; i < NUM; i++)
    {
        int ret = pthread_join(pt[i], nullptr);
        if(ret != 0)
            cerr << "等待线程 " << pt[i] << " 失败!" << endl;
    }

    cout << "所有线程都退出了" << endl;

    return 0;
}
